<template>
    <div class="sys-user-container">
        <splitpanes class="default-theme">
            <pane size="20" >
                <org-tree @node-click="nodeClick"/>
            </pane>
            <pane size="80">
                <a-card class="mb-2">
                    <common-form
                        :model="state.queryForm"
                        name="menu-form"
                        @query="handleQuery"
                        @add="handleAdd"
                        @reset="handleReset"
                    >
                        <a-form-item
                            label="账号"
                            name="account"
                            class="w-1/2.5"
                        >
                            <a-input v-model:value="state.queryForm.account"/>
                        </a-form-item>
                        <a-form-item
                            label="姓名"
                            name="realName"
                            class="w-1/2.5"
                        >
                            <a-input v-model:value="state.queryForm.realName"/>
                        </a-form-item>
                        <a-form-item
                            label="职位名称"
                            name="posName"
                            class="w-1/2.5"
                        >
                            <a-input v-model:value="state.queryForm.posName"/>
                        </a-form-item>
                        <a-form-item
                            label="手机号码"
                            name="phone"
                            class="w-1/2.5"
                        >
                            <a-input v-model:value="state.queryForm.phone"/>
                        </a-form-item>
                    </common-form>
                </a-card>
                <a-card class="h-full sys-user-card-body">
                    <common-table 
                        :columns="columns" 
                        :data="state.tableData"
                        :pagination="{
                                total: state.tableParams.total,
                                current: state.tableParams.page,
                                pageSize: state.tableParams.pageSize,
                                showQuickJumper: true,
                                showSizeChanger: true,
                                pageSizeOptions:['2','5','10','20'],
                                showTotal:(total:number) => `总数: ${total}`
                        }"
                        :loading="state.loading"
                        @change="changePagination"
                    >
                        <template #bodyCell="{ column, text, record }">
                            <template v-if="column.dataIndex === 'avatar'">
                                <a-avatar :src="computedAvatarUrl(record.avatar)" shape="square" size="small">
                                    <template #icon><UserOutlined /></template>
                                </a-avatar>
                            </template>
                            <template v-if="column.dataIndex === 'accountType'">
                                <template v-for="item in useMapDictList('AccountTypeEnum')">
                                    <a-tag color="green" v-if="record.accountType == 666 && record.accountType == item.value">{{ item.label }}</a-tag>
                                    <a-tag color="cyan" v-else-if="record.accountType == 777 && record.accountType == item.value">{{ item.label }}</a-tag>
                                    <a-tag color="blue" v-else-if="record.accountType == 888 && record.accountType == item.value">{{ item.label }}</a-tag>
                                    <a-tag color="purple" v-else-if="record.accountType == 999 && record.accountType == item.value">{{ item.label }}</a-tag>
                                </template>
                            </template>
                            <template v-if="column.dataIndex === 'status'">
                                <a-switch v-model:checked="record.status" :checkedValue="1" @change="changeStatus(record)"/>
                            </template>
                            <template v-if="column.dataIndex ==='history'">
                                <div style="cursor: pointer;">
                                    <edit-record-history :row="record"/>
                                </div>
                            </template>
                            <template v-if="column.dataIndex === 'operation'">
                                <div class="w-full">
                                    <EditOutlined class="mr-2" @click="handleEdit(record)"/>

                                    <a-popconfirm
                                        title="确定删除?"
                                        @confirm="handleDelete(record)"
                                    >
                                        <DeleteOutlined class="mr-2"/>
                                    </a-popconfirm>

                                    <a-button danger class="mr-2" @click="resetUserPwd(record)">重置密码</a-button>
                                    <a-button type="primary">解除锁定</a-button>
                                </div>
                            </template>
                        </template>
                    </common-table>
                </a-card>
            </pane>
        </splitpanes>

        <edit-user ref="editUserRef" :orgData="state.orgTreeData" @handle-query="handleQuery"/>
    </div>
</template>

<script lang="ts" setup name="sysUser">
import { computed, ref, onMounted,reactive,h } from "vue";
import {apiSysOrgListGet} from '@/api/sys/sysOrg'
import { apiSysUserDeletePost, apiSysUserPagePost, apiSysUserResetPwdPost, apiSysUserSetStatusPost } from "@/api/sys/apiUser";
// @ts-ignore
import { Splitpanes, Pane } from 'splitpanes'
import orgTree from "../org/components/orgTree.vue";
import CommonForm from '@/components/common-form/index.vue'
import CommonTable from '@/components/common-table/index.vue'
import type { ResType } from "@/api/types";
import type { TableParamsResType } from "../onlineUser/type";
import type { ItemType } from "./type";
import {EditOutlined,DeleteOutlined} from '@ant-design/icons-vue'
import editRecordHistory from "@/components/self/edit-record-history.vue";
import { useMapDictList } from "@/hooks";
import EditUser from "./components/EditUser.vue";
import type { OrgDataType } from "../org/type";
import { showMsg } from "@/utils";

// 和role一样暂时关闭，会出现role更新一个角色禁用，用户这边由于缓存问题无法获取新列表
// 定义组件名称
defineOptions({
    name: 'sysUser'
})

const editUserRef = ref<InstanceType<typeof EditUser>>()
const state = reactive({
    queryForm:{
        orgId: -1,
        account: undefined,
		realName: undefined,
		phone: undefined,
		posName: undefined
    } as any,
    loading:false,
    tableData:[] as ItemType[],
    tableParams: {
		page: 1,
		pageSize: 10,
		total: 0 as any,
	},
    tenantId:undefined as any,
    orgTreeData:[] as OrgDataType[]
})

const columns :any[]= [
    {
        title: '序号',
        align: "center",
        width: 60,
        customRender: ({ index }:{index:number}) => {
            return `${ index + 1 }`;
        },
    },
    {
        title: '头像',
        dataIndex: 'avatar',
        key: 'avatar',
        align: 'center',
        width: 100,
    },
    {
        title: '账号',
        dataIndex: 'account',
        key: 'account',
        align: 'center',
        width: 150,
    },  
    {
        title: '姓名',
        dataIndex: 'realName',
        key: 'realName',
        align: 'center',
        width: 120,
    },
    {
        title: '手机号码',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center',
        width: 120,
        ellipsis: true
    },
    {
        title: '账号类型',
        dataIndex: 'accountType',
        key: 'accountType',
        align: 'center',
        width: 110,
    },
    {
        title: '角色集合',
        dataIndex: 'roleName',
        key: 'roleName',
        align: 'center',
        width: 150,
        ellipsis: true,
    },
    {
        title: '所属机构',
        dataIndex: 'orgName',
        key: 'orgName',
        align: 'center',
        width: 120,
    },
    {
        title: '职位名称',
        dataIndex: 'posName',
        key: 'posName',
        align: 'center',
        ellipsis: true,
        width: 120,
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        width: 120,
    },
    {
        title: '排序',
        dataIndex: 'orderNo',
        key: 'orderNo',
        align: 'center',
        width: 100,
    },
    {
        title: '修改记录',
        dataIndex: 'history',
        key: 'history',
        align: 'center',
        width: 120,
    },
    {
        title: '操作',
        align: 'center',
        key:"operation",
        dataIndex: 'operation',
        width: 250,
        fixed: 'right',
    }
]

const computedAvatarUrl = (url: string) => {
	return import.meta.env.VITE_API_URL + '/' + url	
}

const handleReset = async() => {
    state.queryForm = {}
    handleQuery()
}

const handleQuery = async ()=>{
    state.loading = true
    const params = Object.assign({},state.queryForm,state.tableParams) 
    const res = await apiSysUserPagePost({...params}) as ResType<TableParamsResType<ItemType>>
    state.tableData = res.data.result.items ?? []
    state.tableParams.total = res.data.result.total
    state.loading = false
}

const changePagination = (pagination:{current:number,pageSize:number})=>{
    state.tableParams.page = pagination.current
    state.tableParams.pageSize = pagination.pageSize
    handleQuery()
}

const handleAdd = () => {
    setTimeout(()=>{
        editUserRef.value?.handleOpen({id: undefined, birthday: '2000-01-01', sex: 1, tenantId: state.tenantId, orderNo: 100, cardType: 0, cultureLevel: 5})
    },100)
}

const handleEdit = (record: any) => {
    setTimeout(()=>{
        editUserRef.value?.handleOpen(record)
    },100)

}

const handleDelete = async(record: ItemType) => {
    await apiSysUserDeletePost({id:record.id})
    await handleQuery()
    showMsg('删除成功','success')
}

const nodeClick = async(node: any) => {
    state.queryForm.orgId = node.id
	state.queryForm.account = undefined;
	state.queryForm.realName = undefined;
	state.queryForm.phone = undefined;
	state.tenantId = node.tenantId;
	await handleQuery();
}

// 查询机构数据
const loadOrgData = async ()=>{
    state.loading = true
    const res = await apiSysOrgListGet(0) as ResType<OrgDataType[]>
    state.orgTreeData = res.data.result ?? []
    state.loading = false
}

const resetUserPwd = async(row:ItemType) =>{
    const res = await apiSysUserResetPwdPost({id:row.id}) as ResType<string>
    showMsg(`重置成功,密码：${res.data.result}`,'success')
}

// 账号禁用状态修改
const changeStatus = async (row:ItemType)=>{
    await apiSysUserSetStatusPost({id:row.id,status:row.status ? 1 : 2})
    showMsg('状态设置成功','success')
    await handleQuery()
}

onMounted(async() => {
    await loadOrgData()
    await handleQuery()
});
</script>


<style lang="scss" scoped>
.sys-user-container{
    .sys-user-card-body{
        :deep(.ant-card-body){
            height: 100%;
        }
    }
}
:deep(.ant-table-cell-fix-right){
    // right: 0 !important;
}
</style>